package com.hgd.igreencar.nettytest;

import com.hgd.igreencar.biz.IVehicleExhaustBiz;
import com.hgd.igreencar.dao.VehicleExhaustMapper;
import com.hgd.igreencar.entity.RpcRequest;
import com.hgd.igreencar.entity.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.UUID;
@Component
public class ServerHandler extends ChannelInboundHandlerAdapter {
    //接收client发送的消息
    @Autowired
    private VehicleExhaustMapper vehicleExhaustMapper;

    public static ServerHandler serverHandler;

    @PostConstruct
    public void init(){
        serverHandler = this;
        serverHandler.vehicleExhaustMapper = this.vehicleExhaustMapper;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        System.out.println("接收到客户端信息：" + request.toString());
        System.out.println(request.getVehicleExhaust().toString());
        serverHandler.vehicleExhaustMapper.save(request.getVehicleExhaust());
        System.out.println("!!!!!!!!!!!");
        //返回的数据结构
        RpcResponse response = new RpcResponse();
        response.setId(UUID.randomUUID().toString());
        response.setData("server响应结果");
        response.setStatus(1);
        ctx.writeAndFlush(response);
    }

    //通知处理器最后的channelRead()是当前批处理中的最后一条消息时调用

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("服务器端接收数据完毕");
        ctx.flush();
    }

    //读操作时捕获到异常时调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    //客户端和服务端连接成功时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

}
